<template>
    <el-dialog
        :title="type == 'add' ? '添加': '修改'"
        v-model="visible"
        width="400px"
    >
        <el-form
            :model="ruleForm"
            :rules="rules"
            ref="formRef"
            label-width="100px"
            class="from"
        >
            <el-form-item label="名称:" prop="description">
                <el-input type="text" v-model="ruleForm.description"></el-input>
            </el-form-item>
            <el-form-item label="激活:" prop="isActive">
                <el-checkbox v-model="ruleForm.isActive" label=""></el-checkbox>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { reactive, ref, toRefs, defineComponent } from 'vue';

export default {
    name: 'AddDialog',
    props: {
        url: String,
        type: String,
        reload: Function,
        save: Function
    },
    setup(props) {
        const formRef = ref(null);
        const state = reactive({
            visible: false,
            ruleForm: {
                id: '',
                description: '',
                isActive: true
            },
            rules: {
                description: [
                    {
                        required: 'true',
                        message: '名称不能为空',
                        trigger: ['change', 'blur']
                    },
                ]
            }
        });

        const open = () => {
            setForm({});
            state.visible = true;
        }

        const edit = (dataItem) => {
            setForm(dataItem);
            state.visible = true;
        }

        const setForm = (dataItem) => {
            state.ruleForm.id = dataItem.id;
            state.ruleForm.description = dataItem.description;
            state.ruleForm.isActive = dataItem.isActive ?? true;
        }

        const close = () => {
            state.visible = false;
        }

        const submitForm = () => {
            formRef.value.validate((valid) => {
                if (valid) {
                    props.save(state.ruleForm)
                }
            })
        }

        return {
            ...toRefs(state),
            open,
            edit,
            close,
            formRef,
            submitForm
        }
    }
}
</script>

